package design.patterns.factorymode.factory;

import design.patterns.factorymode.service.BMW;
import design.patterns.factorymode.service.Benz;
import design.patterns.factorymode.api.CarFactoryInterface;

import java.io.IOException;
import java.util.Map;

/**
 * @Description :
 * @author: cww
 * @DateTime: 2018-07-02 20:49
 */

public class CarFactoryStepOne {

    /**
     * 根据类型来创建对象,传入的key需要if多次
     * @param key
     * @return
     */
    public CarFactoryInterface getCar(String key){
        if ("BMW".equals(key)){
            return new BMW();
        }else if ("Benz".equals(key)){
            return new Benz();
        }else {
            return null;
        }
    }

    /**
     * 根据类型生产对象
     * 反射的应用
     * @param className
     * @return
     */
    public CarFactoryInterface getCarByClass(String className){
        try {
            CarFactoryInterface car = (CarFactoryInterface) Class.forName(className).newInstance();
            return car;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据类型生产对象
     * 反射的应用
     * @param key
     * @return
     */
    public CarFactoryInterface getCarByClassKey(String key) throws IOException {
        try {
            Map<String,String> map = new PropertiesReader().getProperties();
            CarFactoryInterface car = (CarFactoryInterface) Class.forName(map.get(key)).newInstance();
            return car;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
